package day52.basic.service.impl;

import day52.basic.commonenum.ErrorCode;
import day52.basic.constants.Constant;
import day52.basic.domain.dto.SmsVerifyDto;
import day52.basic.exception.CustomException;
import day52.basic.service.IVerifyCodeService;
import day52.basic.util.AjaxResult;
import day52.basic.util.StrUtils;
import day52.basic.util.VerifyCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class VerifyCodeServiceImpl implements IVerifyCodeService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public AjaxResult getImgCode(String imageCodeKey) {
        //生成四位随机数
        String code = StrUtils.getComplexRandomString(4);
        //产生图形验证码
        String verifyCode = VerifyCodeUtils.VerifyCode(115,40,code);
        //保存code到redis
        redisTemplate.opsForValue().set(imageCodeKey,code,5, TimeUnit.MINUTES);
        //将图片验证码返回成base64码
        return AjaxResult.me().setResultObj(verifyCode);
    }

    @Override
    public AjaxResult getSmsCode(SmsVerifyDto dto) {
        //从redis中获取图形验证码
        String imageCode = (String)redisTemplate.opsForValue().get(dto.getImageCodeKey());
        //判断图形验证码是否存在
        if(imageCode == null){
            throw new CustomException(ErrorCode.IMAGECODE_TIME_OUT.getCode());
        }
        //通过前端传递的uuid从redis中获取，和传递过来的图形验证码进行比对（忽略大小写）
        if (!imageCode.equalsIgnoreCase(dto.getImageCode())) {
            throw new CustomException(ErrorCode.IMAGECODE_ERROR.getCode());
        }
        //通过手机号拼接业务键去redis中查询
        String smsKey = dto.getPhone() + Constant.REGISTER_KEY;
        String smsCodeValue = (String) redisTemplate.opsForValue().get(smsKey);
        String smsCode;
        //已过期或者第一次来获取验证码
        if (smsCodeValue == null) {
            //生成验证码
            smsCode = StrUtils.getRandomString(6);
            //发送短信
//            SmsihuyiUtil.sendSms(dto.getPhone(),smsCode);
            System.out.println(smsCode);
        } else {
            //重新发送
            Long sendTime = Long.valueOf(smsCodeValue.split(":")[1]);
            if(System.currentTimeMillis() - sendTime < 1*60*1000){
                throw new CustomException("重复发送！！！别搞事！！！");
            }
            //发送老的验证码
            smsCode =  smsCodeValue.split(":")[0];
            //发送短信
//            SmsihuyiUtil.sendSms(dto.getPhone(),smsCode);
            System.out.println(smsCode);
        }
        //保存redis刷新过期时间
        redisTemplate.opsForValue().set(smsKey, smsCode + ":" + System.currentTimeMillis(), 3, TimeUnit.MINUTES);
        return AjaxResult.me();
    }
}
